package com.roc.web.action.merinfo;

/**
 * @author zbl
 * @date 2014-08-09
 * 正式商户查询
 * */
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.roc.bean.JsonBean;
import com.roc.bean.MerinfoDetail;
import com.roc.bean.MerinfoSearchBean;
import com.roc.bean.TermBean;
import com.roc.dao.operator.IPowerInfoDao;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.AuditingItem;
import com.roc.pojo.EsmidinfoMerinfo;
import com.roc.pojo.EsmidinfoTmp;
import com.roc.pojo.MerinfoStatusChange;
import com.roc.pojo.Negotiation;
import com.roc.pojo.Operators;
import com.roc.pojo.OrgBean;
import com.roc.pojo.TblEditMchtInf;
import com.roc.pojo.TblMchtInf;
import com.roc.pojo.TblTfrHisTrnLog;
import com.roc.pojo.Termapply;
import com.roc.service.IAgentService;
import com.roc.service.IExcelService;
import com.roc.service.IMerchantServices;
import com.roc.service.IPagenitionService;
import com.roc.service.ITerminalService;
import com.roc.service.IUserService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.Utils;
import com.roc.util.constant.AuditingResultCodeType;
import com.roc.util.constant.ConfigMerinfoUtil;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.MerchantStatus;
import com.roc.util.constant.MerinfoStatus;
import com.roc.util.constant.Role;
import com.roc.web.action.estrn.EstrnHisInfoSearchCondition;

import net.sf.json.JSON;
import net.sf.json.JSONObject;

@Controller
@Namespace("/formalMerinfo")
@SuppressWarnings("all")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class FormalMerinfoAction extends PaginationBaseAction {
	private static Logger logger = Logger.getLogger(FormalMerinfoAction.class);
	
	@Autowired
	private IMerchantServices merinfoService;
	@Autowired
	private IUserService  userService;
	@Autowired
	private IPagenitionService pagenitionService; 
	@Autowired
	private IPageService pageService; 
	@Autowired
	IExcelService excelService;
	
	private FormalMerinfoSearchCondtion searchCondition;
	private TblMchtInf merinfo;
	private Operators op;
	private JsonBean jsonBean;
	
	private MerinfoStatusChange merinfoStatusChange;
	@Autowired
	private IPowerInfoService powerInfoService;
	private List<Operators> agentList;
	private String oldAgentId;
	private String newAgentId;
	
	private InputStream excelFile;
	private String excelName;
		// 商户查询初始化
		@Action(value = "jspInit", results = {	
				@Result(name =SUCCESS, location = "/pages/merinfo/merinfoList.jsp"),
				@Result(name = ERROR, location = "/error.jsp") })
		public String merinfoListInit() {
			try {
				op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
				//getRequest().setAttribute("roleType", op.getRoleType()); //登录人角色
				 return SUCCESS;
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
				e.printStackTrace();
				addActionError(e.getMessage());
				return ERROR;
			}

		}

		// 商户(审核)查询
		@Action(value = "queryList", results = {
				@Result(name = SUCCESS, location = "/pages/merinfo/merinfoList.jsp"),
				@Result(name = ERROR, location = "/error.jsp") })
		public String queryList() {
			 op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			try {
				if (searchCondition == null) {
					searchCondition = (FormalMerinfoSearchCondtion) getSearchConditionFromSession();
					if (searchCondition == null) {
						searchCondition = new FormalMerinfoSearchCondtion();
					}
				}
				
				Map<String, String> map=powerInfoService.queryRealIdByOpId(op.getSuperiorId(), op.getRoleType(), op.getId(), op.getOrgCode());
	            String orgCode=map.get("orgCode");
	            String superRole= map.get("superRole");
	            String opRealId =map.get("opRealId");
	            searchCondition.setGroupCd(map.get("groupCd"));
				//是否选择查询二级代理商
				if(null == searchCondition.getSonCode() || searchCondition.getSonCode().equals("-1")){
					 if(null == searchCondition.getParentCode() || searchCondition.getParentCode().equals("-1")){
								searchCondition.setOpId(opRealId);//运营人员取上级id
								searchCondition.setRoleId(superRole);// 角色
						}
					 else{
						 searchCondition.setOpId(searchCondition.getParentCode());//一级代理id
						 searchCondition.setRoleId(Role.AGENT.getCode());
					 }
				}else{
					searchCondition.setOpId(searchCondition.getSonCode());//二级代理id
					searchCondition.setRoleId(Role.AGENT.getCode());
				}
				searchCondition.setLoginId(searchCondition.getOpId());//真正登录人
				searchCondition.setOrgCode(orgCode);//收单机构号
				if("".equals(op.getGroupCd())||null==op.getGroupCd()){
					searchCondition.setGroupCd("99");
				}else{
					searchCondition.setGroupCd(op.getGroupCd());
					
				}
				if(!"".equals(op.getOneagentid())){
					searchCondition.setOneOrgCode(op.getOneagentid());//机构号
				}
     			if(op.getRoleType().equals(Role.MERCHANT.getCode())){//商户角色
					searchCondition.setMerchantNo(op.getAccountNo());
				}
				int rows = pageService.countSQL(searchCondition);
				List<MerinfoSearchBean> msList = new ArrayList<MerinfoSearchBean>();
				if (rows > 0) {
					searchRsList = pageService.findAllSQL(searchCondition, 
														calcuStart(getCurrentPage()),
														Constance.PAGE_MAX_SIZE);
					if (searchRsList.size() > 0 && searchRsList != null) {
						Iterator iterator = searchRsList.iterator();
						while (iterator.hasNext()) {
							Object[] obj = (Object[]) iterator.next();
							MerinfoSearchBean msb = new MerinfoSearchBean();
							msb.setMid(Constance.Null2EmptyTrim(obj[0]));
							msb.setMerName(Constance.Null2EmptyTrim(obj[1]));
							msb.setMerBrName(Constance.Null2EmptyTrim(obj[2]));
							msb.setMerKind(Constance.Null2EmptyTrim(obj[3]));
							msb.setPerName(Constance.Null2EmptyTrim(obj[4]));
							String phone=Constance.Null2EmptyTrim(obj[5]);
							if(null!=op.getAgentType() && !op.getAgentType().equals("1") && null!=phone && phone.length()>4){
								msb.setPerPhone(phone.substring(0, 3)+"****"+phone.substring(phone.length()-4));//手机号
							}else{
								msb.setPerPhone(phone);//手机号
							}
							
							msb.setInterContact(Constance.Null2EmptyTrim(obj[6]));
							String cardNo=Constance.Null2EmptyTrim(obj[7]);
							if(null!=op.getAgentType() && !op.getAgentType().equals("1") && null!=cardNo && cardNo.length()>4){
								msb.setCardNo(cardNo.substring(0,3)+"****"+cardNo.substring(cardNo.length()-4));//证件号
							}else{
								msb.setCardNo(cardNo);//证件号
							}
							
							msb.setFlagCode(Constance.Null2EmptyTrim(obj[8]));
							msb.setAddr(Constance.Null2EmptyTrim(obj[9]));
							msb.setFlag(MerinfoStatus.getName(Constance.Null2EmptyTrim(obj[10])));//状态
							msb.setBus_lic(Constance.Null2EmptyTrim(obj[11]));//审核人员名称
							msb.setCompanyName(Constance.Null2EmptyTrim(obj[12]));//所属分公司
							msb.setOneAgentName(Constance.Null2EmptyTrim(obj[13]));//所属代理商
							msb.setAgentId(Constance.Null2EmptyTrim(obj[14]));//直属代理商
							msb.setRsvl(Constance.Null2EmptyTrim(obj[15]));//结算银行账户名称
							String account=Constance.Null2EmptyTrim(obj[16]);
							/*if(account!=null && account.length()>4){
								msb.setRsvl3(account.substring(0, 4)+"****"+account.substring(account.length()-4));//结算银行账户
							}else{*/
								msb.setRsvl3(account);//结算银行账户
							//}
							
							msb.setAmount1(Constance.Null2EmptyTrim(obj[17]));//结算银行名称
							msb.setAmount2(Constance.Null2EmptyTrim(obj[18]));//联行号
							msb.setGroupCd(Constance.Null2EmptyTrim(obj[21])); //商户类型
							/*String[] cycleList=merinfoService.queryMchtBizDealArray(msb.getMid(),true,true);//根据商户查询结算周期
							msb.setMerCycle(cycleList);*/
							String[] productCodeFlag=merinfoService.queryMchtBizDealArray(msb.getMid(), true, false);
							String[] cycleList={"",""};
							if(Constant.STR_NUMBER_ONE.equals(msb.getGroupCd()) && (Arrays.asList(productCodeFlag).contains(ConfigMerinfoUtil.DIRECT_FUNCTION_T1) ||
									Arrays.asList(productCodeFlag).contains(ConfigMerinfoUtil.DIRECT_FUNCTION_T0))){	//结算方式处理
								cycleList[0]=Constance.Null2EmptyTrim(obj[25]);
								if(null!=Constance.Null2EmptyTrim(obj[26]) && !Constance.Null2EmptyTrim(obj[26]).equals("")){
									String j="";
									if(null!=cycleList[0] && !cycleList[0].equals("")){
										j="+";
									}
									cycleList[1]=j+Constance.Null2EmptyTrim(obj[26]);
								}
							}else{
								cycleList[0]=Constance.Null2EmptyTrim(obj[19]);
								if(null!=Constance.Null2EmptyTrim(obj[20]) && !Constance.Null2EmptyTrim(obj[20]).equals("")){
									String j="";
									if(null!=cycleList[0] && !cycleList[0].equals("")){
										j="+";
									}
									cycleList[1]=j+Constance.Null2EmptyTrim(obj[20]);
								}
							}
							msb.setMerCycle(cycleList);
							msb.setNationCd(Constance.Null2EmptyTrim(obj[22]).trim());
							msb.setIsGroup(Constance.Null2EmptyTrim(obj[23]));
							msb.setApplDate(Constance.Null2EmptyTrim(obj[24]));
							if("2".equals(op.getGroupCd())||op.getRoleType().equals(Role.SYSTEM.getCode())||op.getRoleType().equals(Role.OPERATORS_LEAD.getCode())
									||op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())||op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode())){
					        	msb.setTermProperty(Constance.Null2EmptyTrim(obj[27]));
								msb.setCertifDate(Constance.Null2EmptyTrim(obj[28]));
								msb.setBusiLiceDate(Constance.Null2EmptyTrim(obj[29]));
							    msb.setDevelopPerson(Constance.Null2EmptyTrim(obj[30]));
							}
							msList.add(msb);
						}
					}

				}
				this.setTotalPage(this.calcuTotalPage(rows));
				getRequest().setAttribute("COUNT", rows);//当前条件统计总数
				getRequest().setAttribute(SEARCH_RS_LIST, msList);
				getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
				getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
				setSearchToConditionSession(searchCondition);
			 
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
				addActionError(e.getMessage());
				return ERROR;
			}
				return SUCCESS;
		}
		
		 
		
		/**
		 * 冻结商户
		 * */
		@Action(value = "changeMerinfoStatus",results={
				 @Result(name=SUCCESS,type="json",params={"json","${jsonBean}"})
		})
		public String changeMerinfoStatus(){
			 op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			  jsonBean=new JsonBean();
				try {
					if(op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode()) ||
					   op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode())	){ //风控角色进行冻结
						jsonBean=merinfoService.changeMerinfoStatus(merinfo.getId(), merinfo.getStatus(), op.getAccountNo());
					}else{
						jsonBean.setCode("9999");
						jsonBean.setCodeDesc("暂无权限");
					}
					//json=JSONObject.fromObject(jsonBean).toString();
				} catch (ServiceException e) {
					logger.error(e.getMessage(),e);
					jsonBean.setCode("9999");
					jsonBean.setCodeDesc("未知错误");
					//json=JSONObject.fromObject(jsonBean).toString();
				}
				return SUCCESS;
		}
		/**
		 * 填写冻结商户初始化页面详情merinfoList
		 * @return
		 * @throws ServiceException 
		 */
	        @Action(value = "freezePage", results = { 
	                @Result(name = SUCCESS, location = "/pages/merinfo/freezePage.jsp"),
	                @Result(name = INPUT, location = "/pages/merinfo/merinfoList.jsp")
	        })
	            public String freezePage() throws ServiceException{
	                    op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
	                    jsonBean=new JsonBean();
	                    
	                    TblMchtInf mer = new TblMchtInf();
	                    mer=merinfoService.queryMerinfoDetailInfo(merinfo.getId(), true,op.getAgentType());
                            try {
                            
                                if(op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode()) ||
                                   op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode())    ){ //风控角色进行冻结
                                        jsonBean=merinfoService.changeMerinfoStatusCheck(merinfo.getId(), merinfo.getStatus(), op.getAccountNo());
                                }else{
                                        jsonBean.setCode("9999");
                                        jsonBean.setCodeDesc("暂无权限");
                                }
                            } catch (ServiceException e) {
                                    logger.error(e.getMessage(),e);
                                    jsonBean.setCode("9999");
                                    jsonBean.setCodeDesc("未知错误");
                            }
                            
                            if(jsonBean.getCode().equals("9999")){
                                getRequest().setAttribute("jsonResult", jsonBean.getCodeDesc());
                                addActionMessage(jsonBean.getCodeDesc());
                                return INPUT;
                            }else{
                                getRequest().setAttribute("jsonResult", jsonBean.getCodeDesc());
                                getRequest().setAttribute("operator", op.getRealName());//当前操作员信息
                                if(null!=mer.getStatusChange() && !"".equals(mer.getStatusChange())){
                                	getRequest().setAttribute("detail",mer.getStatusChange());//解冻可查看之前冻结的原因
                                }
                                addActionMessage(jsonBean.getCodeDesc());
                                return SUCCESS;
                            }
	            }
	        /**
                 * 冻结商户
                 * */
	        @Action(value = "freeze", results = { 
	                @Result(name = SUCCESS, location = "/pages/merinfo/merinfoList.jsp")
                })
                public String changeMerinfoStatus2(){
                         op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
                          jsonBean=new JsonBean();
                                try {
                                    merinfoStatusChange.setAgentId(op.getId());
                                    merinfoStatusChange.setAgentName(op.getRealName());
                                    merinfoStatusChange.setCreatetime(Constance.formatDate(Constance.DATA_FORMAT_PATTERN_01));
                                    merinfoStatusChange.setMid(merinfo.getId());
                                    
                                    if(null != merinfo.getStatus() && merinfo.getStatus().equals("03")){
                                        merinfoStatusChange.setStatus("0");
                                    }else if (null != merinfo.getStatus() && merinfo.getStatus().equals("01")) {
                                        merinfoStatusChange.setStatus("1");
                                    }else if (null != merinfo.getStatus() && merinfo.getStatus().equals("02")) {
                                        merinfoStatusChange.setStatus("9");
                                    }
                                    
                                    if(op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode()) ||
                                       op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode())    ){ //风控角色进行冻结
                                            jsonBean=merinfoService.changeMerinfoStatus2(merinfo.getId(), merinfo.getStatus(), op.getAccountNo(),merinfoStatusChange);
                                    }else{
                                            jsonBean.setCode("9999");
                                            jsonBean.setCodeDesc("暂无权限");
                                    }
                                        //json=JSONObject.fromObject(jsonBean).toString();
                                } catch (ServiceException e) {
                                        logger.error(e.getMessage(),e);
                                        jsonBean.setCode("9999");
                                        jsonBean.setCodeDesc("未知错误");
                                        //json=JSONObject.fromObject(jsonBean).toString();
                                }
                                
                                if(jsonBean.getCode().equals("9999")){
                                    getRequest().setAttribute("jsonResult", jsonBean.getCodeDesc());
                                    addActionMessage(jsonBean.getCodeDesc());
                                    return SUCCESS;
                                }else{
                                    getRequest().setAttribute("jsonResult", jsonBean.getCodeDesc());
                                    getRequest().setAttribute("operator", op.getRealName());//操作员名称
                                    addActionMessage(jsonBean.getCodeDesc());
                                    return SUCCESS;
                                }
                }
	        
	     // 商户查询导出excel
	   @Action(value = "exportmerinfoExcel", results = {@Result(name = "success", type = "stream", params = {
	    				"contentType", "application/vnd.ms-excel", "inputName","excelFile", 
	    				"contentDisposition","attachment;filename=${excelName}.xls", "bufferSize","1024*3" }),
	    			@Result(name = "error", location = "/pages/merinfo/merinfoList.jsp") })
	   public String exportmerinfoExcel() throws Exception {
	    		logger.info("导出商户查询");
				 Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
					
					if(searchCondition==null){
						searchCondition=(FormalMerinfoSearchCondtion)getSearchConditionFromSession();
						if(searchCondition==null){
							searchCondition=new FormalMerinfoSearchCondtion();
						}
					}
	    		try {
					if(null == searchCondition.getSonCode() || searchCondition.getSonCode().equals("-1")){
						 if(null == searchCondition.getParentCode() || searchCondition.getParentCode().equals("-1")){
							 searchCondition.setOpId(String.valueOf(op.getId()));//当前操作人员
						 }else{
							 searchCondition.setOpId(searchCondition.getParentCode());//一级代理id
						 }
					}else{
						searchCondition.setOpId(searchCondition.getSonCode());//二级代理id
					}
					searchCondition.setOrgCode(op.getOrgCode());//当前查询人员所属机构
					searchCondition.setRoleId(op.getRoleType());// 角色
					int rows=pagenitionService.countSQL(searchCondition);
					if(rows>0){
						searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), rows);
					}
					List<MerinfoSearchBean> merfList = new ArrayList<MerinfoSearchBean>();
					queryExcelList(merfList,searchRsList);
					
					HSSFWorkbook work=excelService.exportmerinfoList(merfList);

					 ByteArrayOutputStream output = new ByteArrayOutputStream();  
					         work.write(output);  
					   
					        byte[] ba = output.toByteArray();  
					         excelFile = new ByteArrayInputStream(ba);  
					         output.flush();  
					         output.close();  
					
		}catch (ServiceException e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			
		}
		
		return SUCCESS;
	}
	    	private void queryExcelList(List<MerinfoSearchBean> merfList,
	    			List<Object> searchRsList) {
	    		
	    	    Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
	    		if(searchRsList!=null&&searchRsList.size()>0){
	    			Iterator iterator=searchRsList.iterator();
	    			while (iterator.hasNext()) {
						Object[] obj = (Object[]) iterator.next();
						MerinfoSearchBean msb = new MerinfoSearchBean();
						msb.setMid(Constance.Null2EmptyTrim(obj[0]));
						msb.setMerName(Constance.Null2EmptyTrim(obj[1]));
						msb.setMerBrName(Constance.Null2EmptyTrim(obj[2]));
						String[] cycleList={"",""};
						cycleList[0]=Constance.Null2EmptyTrim(obj[19]);
						msb.setMerKind(Constance.Null2EmptyTrim(obj[3]));
						msb.setPerName(Constance.Null2EmptyTrim(obj[4]));
						String phone=Constance.Null2EmptyTrim(obj[5]);
						if(null!=op.getAgentType() && !op.getAgentType().equals("1") && null!=phone && phone.length()>4){
							msb.setPerPhone(phone.substring(0, 3)+"****"+phone.substring(phone.length()-4));//手机号
						}else{
							msb.setPerPhone(phone);//手机号
						}
						msb.setInterContact(Constance.Null2EmptyTrim(obj[6]));
						String cardNo=Constance.Null2EmptyTrim(obj[7]);
						if(null!=op.getAgentType() && !op.getAgentType().equals("1") && null!=cardNo && cardNo.length()>4){
							msb.setCardNo(cardNo.substring(0,3)+"****"+cardNo.substring(cardNo.length()-4));//证件号
						}else{
							msb.setCardNo(cardNo);//证件号
						}
						msb.setFlagCode(Constance.Null2EmptyTrim(obj[8]));
						msb.setAddr(Constance.Null2EmptyTrim(obj[9]));
						msb.setFlag(MerinfoStatus.getName(Constance.Null2EmptyTrim(obj[10])));//状态
						msb.setBus_lic(Constance.Null2EmptyTrim(obj[11]));//审核人员名称
						msb.setCompanyName(Constance.Null2EmptyTrim(obj[12]));//所属分公司
						msb.setOneAgentName(Constance.Null2EmptyTrim(obj[13]));//所属代理商
						msb.setAgentId(Constance.Null2EmptyTrim(obj[14]));//直属代理商
						msb.setRsvl(Constance.Null2EmptyTrim(obj[15]));//结算银行账户名称
						String account=Constance.Null2EmptyTrim(obj[16]);
							msb.setRsvl3(account);//结算银行账户
						msb.setAmount1(Constance.Null2EmptyTrim(obj[17]));//结算银行名称
						msb.setAmount2(Constance.Null2EmptyTrim(obj[18]));//联行号
						
						if(null!=Constance.Null2EmptyTrim(obj[20]) && !Constance.Null2EmptyTrim(obj[20]).equals("")){
							String j="";
							if(null!=cycleList[0] && !cycleList[0].equals("")){
								j="+";
							}
							cycleList[1]=j+Constance.Null2EmptyTrim(obj[20]);
						}
						msb.setMerCycle(cycleList);
						msb.setGroupCd(Constance.Null2EmptyTrim(obj[21])); 
						msb.setNationCd(Constance.Null2EmptyTrim(obj[22]).trim());
						msb.setIsGroup(Constance.Null2EmptyTrim(obj[23]));
						msb.setApplDate(Constance.Null2EmptyTrim(obj[24]));
						merfList.add(msb);
					}
	    		}
	    		
	    		
	    	}
	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE + "";
	}

	 
	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (FormalMerinfoSearchCondtion) getSession().getAttribute(SEARCH_SESSION_FORMAL_MERINFO_INFO);
	}

	 
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass() throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	 
	@Override
	protected void setSearchConditionToSubClass(BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	 
	@Override
	protected void setSearchToConditionSession(BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_FORMAL_MERINFO_INFO, searchCondition);
	}

	 
	  
 
	@Action(value = "queryMerchtDetail", results = {
			@Result(name = SUCCESS, location = "/pages/merinfo/merchantDetailInfo.jsp"),
			@Result(name = ERROR, location = "/error.jsp") })
	public String queryMerchtDetailByMerchtCd()
	{
		try {
			if (null==merinfo || merinfo.getId() == null || merinfo.getId().equals("")) {
				addActionError("异常，获取商户信息失败");
				return ERROR;
			}
			op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			merinfo=merinfoService.queryMerinfoDetailInfo(merinfo.getId(), true,op.getAgentType());
			getRequest().setAttribute("mcc", ConfigProperties.getHyMccTypeProperties());//mcc
			/*getRequest().setAttribute("provinesMap", ConfigProperties.getUnionProviceProperties());//32域省份*/
			//查询32域信息
			String code32=userService.queryAreaDetailBy32Code(merinfo.getUcBccd());
			getRequest().setAttribute("code32",code32);
			getRequest().setAttribute("choosePosName",ConfigProperties.getSysDB1("PROD_CD",true).get(merinfo.getProductCode()));
			if(Constant.STR_NUMBER_ONE.equals(merinfo.getGroupCD())){
				getRequest().setAttribute("posFunction", ConfigMerinfoUtil.getDirectProductList(ConfigMerinfoUtil.DIRECT_FUNCTION_ALL, true));//获取开通直连产品信息
			}else{
				getRequest().setAttribute("posFunction", ConfigMerinfoUtil.getPosFunction(ConfigMerinfoUtil.ALL_FUNCTION, true));//开通产品信息
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
	}
	/**
	 * 商户分配页面
	 * @return
	 */
	@Action(value = "merInfoAssginInit", results = {
			@Result(name = SUCCESS, location = "/pages/merinfo/merinfoAssign.jsp"),
			@Result(name = ERROR, location = "/error.jsp") })
	public String merInfoAssign(){
		op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			agentList=merinfoService.getSubAgent(op);//取得所有子代理
			Operators oldAgent=merinfoService.findOldAgent(merinfo.getId());//原代理
			//剔除原代理
			for(int i=0;i<agentList.size();i++){
				if(oldAgent.getId()==agentList.get(i).getId()){
					agentList.remove(i);
					break;
				}
			}
			getRequest().setAttribute("oldAgent", oldAgent);
			logger.info("商户分配给代理商初始化页面~");
		} catch (ServiceException e) {
			e.printStackTrace();
			addActionError("加载代理商信息失败~!");
		}
		return SUCCESS;
	}
	@Action(value = "merInfoAssgin", results = {
			@Result(name = SUCCESS, location = "/pages/merinfo/merinfoList.jsp"),
			@Result(name = "failed",type="chain", location = "merInfoAssginInit"),
			@Result(name = ERROR, location = "/error.jsp") })
	public String assignAgent(){
		op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			if(Constance.isEmpty(newAgentId)){
				addActionMessage("重新分配的代理商不存在");
				return "failed";
			}
			Map map=merinfoService.assginMerchtToAgent(merinfo.getId(), oldAgentId, newAgentId,op);
			if(map.containsKey("result")){
				String msg=String.valueOf(map.get("result"));
				addActionMessage(msg);
				return "failed";
			}
			addActionMessage("建立商户代理商关系成功!");
		} catch (ServiceException e) {
			addActionError("重建建立商户代理商关系失败~，请重试");
			e.printStackTrace();
		}
		return SUCCESS;		
	}
	public TblMchtInf getMerinfo() {
		return merinfo;
	}

	public void setMerinfo(TblMchtInf merinfo) {
		this.merinfo = merinfo;
	}

	public FormalMerinfoSearchCondtion getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(FormalMerinfoSearchCondtion searchCondition) {
		this.searchCondition = searchCondition;
	}

	public Operators getOp() {
		return op;
	}

	public void setOp(Operators op) {
		this.op = op;
	}

	public JsonBean getJsonBean() {
		return jsonBean;
	}

	public void setJsonBean(JsonBean jsonBean) {
		this.jsonBean = jsonBean;
	}

    public MerinfoStatusChange getMerinfoStatusChange() {
        return merinfoStatusChange;
    }

    public void setMerinfoStatusChange(MerinfoStatusChange merinfoStatusChange) {
        this.merinfoStatusChange = merinfoStatusChange;
    }

	public List<Operators> getAgentList() {
		return agentList;
	}

	public void setAgentList(List<Operators> agentList) {
		this.agentList = agentList;
	}

	public String getOldAgentId() {
		return oldAgentId;
	}

	public void setOldAgentId(String oldAgentId) {
		this.oldAgentId = oldAgentId;
	}

	public String getNewAgentId() {
		return newAgentId;
	}

	public void setNewAgentId(String newAgentId) {
		this.newAgentId = newAgentId;
	}
	
	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public String getExcelName() {
		String excelName = "商户查询" + Constance.formateDate();

		try {
			excelName = new String(excelName.getBytes(), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			logger.info("生成excel名称失败了！");
		}

		return excelName;

	}

	public void setExcelName(String excelName) {
		this.excelName = excelName;
	}

	
}
